package com.eascs.file;

import java.io.IOException;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.eascs.admin.common.service.BaseSevice;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.dfs.fastdfs.FastDfsClient;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.util.UuidUtil;
import com.eascs.datalist.entity.O2oDataListEntity;
import com.eascs.datalist.service.O2oDataListService;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;

@Service
public class FileService extends BaseSevice {
	
	private final Logger logger = LoggerFactory.getLogger(FileService.class);

	@Autowired
	private O2oDataListService o2oDataListService;
	
	@Autowired
	FileDao fileDao;
	

	@Autowired
	private FastDfsClient fastDfsClient;

	private static String groupName = "grouploan";
	

	@Transactional(transactionManager = "o2oTransactionManager")
	public String upload(MultipartFile file, String datalistCode, String loanapplyno) {
		return fileDao.upload(file, datalistCode, loanapplyno);
	}
	
	@Transactional(transactionManager = "o2oTransactionManager")
	public String sponsorupload(MultipartFile file, String datalistCode, String loanapplyno,String sponsorId) {
		return fileDao.upload_sponsor(file, datalistCode, loanapplyno,sponsorId);
	}
	
	@Transactional(transactionManager = "o2oTransactionManager")
	public String upload(MultipartFile file, String datalistCode, String loanapplyno, String paymentsId) {
		return fileDao.upload(file, datalistCode, loanapplyno, paymentsId);
	}
	
	/**
	 * 更新文件地址
	 * @Title: updateFilePath
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @author user
	 * @param file
	 * @param datalistCode
	 * @param datalistNo
	 * @return
	 * @return boolean
	 * @throws
	 * @date 2016年8月16日 下午4:32:22
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public boolean updateFilePath(MultipartFile file,  String datalistCode, String datalistNo) {
		User user = UserHolder.getUser();
		boolean flag = false;
		
		try {
			String extendName = fastDfsClient.getFileExtName(file.getOriginalFilename());
			String urlPath = fastDfsClient.uploadInputStream(file.getInputStream(), groupName, extendName, null);
			logger.info("FastDFS uploadPath:[{}]", urlPath);
			Date date=new Date();
			//更新文件首先隐删除之前的记录然后新增一条数据
			O2oDataListEntity loanEntity = o2oDataListService.findO2oDataListEntity(datalistNo);
			loanEntity.setIsDelete(StatusContexts.O2O_YES);
			loanEntity.setUpdateTime(date);
			flag = fileDao.updateFileEntity(loanEntity);
			//新增数据
			O2oDataListEntity dataListEntity = new O2oDataListEntity();
			dataListEntity.setUrlpath(urlPath);
			dataListEntity.setOriginalName(file.getOriginalFilename());
			dataListEntity.setDatalistCode(datalistCode);
			dataListEntity.setDatalistName(FileTypeConstants.getDatalistName(datalistCode));
			dataListEntity.setCreatId(user.getNo());
			dataListEntity.setCreatOr(user.getCname());
			dataListEntity.setExtendNmae(extendName);
			dataListEntity.setCreatDate(date);
			dataListEntity.setUpdateTime(date);
			dataListEntity.setIsDelete(StatusContexts.O2O_NO);
			dataListEntity.setLoanapplyNo(loanEntity.getLoanapplyNo());
			int i = o2oDataListService.saveEntity(dataListEntity);
			if (i > 0) {
				flag = true;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
			throw new RuntimeIOException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeIOException(e);
		}
		
		return flag;
	}

	@Transactional(transactionManager = "o2oTransactionManager")
	public String updateFileUpload(MultipartFile file, String datalistCode, String loanapplyno) {
		User user = UserHolder.getUser();
		try {
			String extendName = fastDfsClient.getFileExtName(file.getOriginalFilename());
			String urlPath = fastDfsClient.uploadInputStream(file.getInputStream(), groupName, extendName, null);
			logger.info("FastDFS uploadPath:[{}]", urlPath);
			O2oDataListEntity loanEntity = new O2oDataListEntity();
			loanEntity.setCreatDate(new Date());
			loanEntity.setCreatId(user.getNo());
			loanEntity.setCreatOr(user.getCname());
			loanEntity.setUrlpath(urlPath);
			loanEntity.setDatalistCode(datalistCode);
			loanEntity.setOriginalName(file.getOriginalFilename());
			loanEntity.setDatalistName(FileTypeConstants.getDatalistName(datalistCode));
			loanEntity.setExtendNmae(extendName);
			String datalistNo = fileDao.findString("select datalist_no from o2o_datalist where is_delete=? and loanapply_no=? and datalist_code=?", StatusContexts.O2O_NO, loanapplyno, datalistCode);
			if (!StringUtils.isEmpty(datalistNo)) {
				loanEntity.setDatalistNo(datalistNo);
				loanEntity.setUpdateTime(new Date());
				String sql = "update o2o_datalist set datalist_name=?,extend_nmae=?,original_name=?,urlpath=? where datalist_no=?";
				fileDao.execute(sql, loanEntity.getDatalistName(), loanEntity.getExtendNmae(), loanEntity.getOriginalName(), loanEntity.getUrlpath(), loanEntity.getDatalistNo());
			} else {
				loanEntity.setLoanapplyNo(loanapplyno);
				loanEntity.setUpdateTime(loanEntity.getCreatDate());
				loanEntity.setDatalistNo(UuidUtil.generateShortUuid(4));
				fileDao.insert(loanEntity);
			}
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		}
		return "";
	}
	
	/**
	 * 根据id查询附件信息
	 * @param id
	 * @return
	 */
	public O2oDataListEntity getByidDataList(String id){
		return fileDao.getById(O2oDataListEntity.class, id);
	}
	
	/**
	 * 根据贷款单号和附件类型查询附件信息
	 * @param id
	 * @return
	 */
	public O2oDataListEntity getByBillCodeDataList(String loanapplyNo, String paymentsId){
		String sql = "select * from o2o_datalist od where od.is_delete=? and od.loanapply_no=? and od.datalist_code=? and od.payments_id=?";
		return fileDao.findEntity(sql, O2oDataListEntity.class, StatusContexts.O2O_NO, loanapplyNo, FileTypeConstants.DALIST_TYPE_RPMENT, paymentsId);
	}
	
	/**
	 * 根据还款记录id查询还款凭证
	 * @param id
	 * @return
	 */
	public O2oDataListEntity getByRecordDataList(String loanapplyNo){
		String sql = "select * from o2o_datalist od where od.is_delete=? and od.loanapply_no=? and od.datalist_code=?";
		return fileDao.findEntity(sql, O2oDataListEntity.class, StatusContexts.O2O_NO, loanapplyNo, FileTypeConstants.DALIST_TYPE_RPMENT);
	}
	
	/**
	 * 根据单号id和附件类型查询附件信息
	 * @param id
	 * @return
	 */
	public O2oDataListEntity getByIdAndByType(String loanapplyNo, String type){
		String sql = "select * from o2o_datalist od where od.is_delete=? and od.loanapply_no=? and od.datalist_code=?";
		return fileDao.findEntity(sql, O2oDataListEntity.class, StatusContexts.O2O_NO, loanapplyNo, type);
	}
	
	/**
	 * 根据代偿分期id查询附件
	 * @param id
	 * @return
	 */
	public int getBackDataList(String loanapplyNo, String type){
		String sql = "select count(*) from o2o_datalist od where od.is_delete=? and od.loanapply_no=? and od.datalist_code in(" + type + ")";
		return fileDao.findInteger(sql, StatusContexts.O2O_NO, loanapplyNo);
	}
	
	
	/**
	 * @Description: <p> 隐删除附件 </p>
	 * @author CXW
	 * @date 2016年9月26日 上午11:01:57
	 * @version V1.0
	 * @param dataListEntity
	 * @return int
	 */
	@Transactional(transactionManager = "o2oTransactionManager")
	public int updateEntityById(O2oDataListEntity dataListEntity){
		return fileDao.updateById(dataListEntity);
	}
}
